package com.dss.auto_deploy.quartz.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dss.auto_deploy.constants.Constants;
import com.dss.auto_deploy.quartz.domain.SysJob;
import com.dss.auto_deploy.quartz.dto.SysJobPageDto;
import com.dss.auto_deploy.quartz.service.ISysJobService;
import com.dss.auto_deploy.quartz.service.TimingStrategyHandler;
import com.dss.auto_deploy.quartz.util.ScheduleUtils;
import com.dss.auto_deploy.quartz.util.TaskException;
import com.dss.auto_deploy.quartz.util.TimeExpressionType;
import com.dss.auto_deploy.util.Result;
import com.dss.auto_deploy.util.StringUtils;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 调度任务信息操作处理
 *
 * @author lenovo
 */
@RestController
@RequestMapping("/monitor/job")
@Api(tags = "定时任务")
@RequiredArgsConstructor(onConstructor = @_(@Autowired))
public class SysJobController {
    private final ISysJobService jobService;
    private final TimingStrategyHandler timingStrategyHandler;

    /**
     * 查询定时任务列表
     */
    @GetMapping("/list")
    public Result list(SysJobPageDto pageDto) {
        Page<SysJob> list = jobService.selectJobList(pageDto);
        return Result.success(list);
    }


    /**
     * 获取定时任务详细信息
     */
    @GetMapping(value = "/{jobId}")
    public Result getInfo(@PathVariable("jobId") Long jobId) {
        return Result.success(jobService.selectJobById(jobId));
    }

    /**
     * 新增定时任务
     */
    @PostMapping
    public Result add(@RequestBody SysJob job) throws SchedulerException, TaskException {
        try {
            timingStrategyHandler.validate(job.getCronExpression());
        }catch (Exception e){
            return Result.fail("新增任务'" + job.getJobName() + "'失败，Cron表达式不正确");
        }
        if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI)) {
            return Result.fail("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'rmi'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.LOOKUP_LDAP, Constants.LOOKUP_LDAPS})) {
            return Result.fail("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'ldap(s)'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.HTTP, Constants.HTTPS})) {
            return Result.fail("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'http(s)'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), Constants.JOB_ERROR_STR)) {
            return Result.fail("新增任务'" + job.getJobName() + "'失败，目标字符串存在违规");
        } else if (!ScheduleUtils.whiteList(job.getInvokeTarget())) {
            return Result.fail("新增任务'" + job.getJobName() + "'失败，目标字符串不在白名单内");
        }
        return Result.success(jobService.insertJob(job));
    }

    /**
     * 修改定时任务
     */
    @PutMapping
    public Result edit(@RequestBody SysJob job) throws SchedulerException, TaskException {
        try {
            timingStrategyHandler.validate(job.getCronExpression());
        }catch (Exception e){
            return Result.fail("修改任务'" + job.getJobName() + "'失败，Cron表达式不正确");
        }
        if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI)) {
            return Result.fail("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'rmi'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.LOOKUP_LDAP, Constants.LOOKUP_LDAPS})) {
            return Result.fail("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'ldap(s)'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.HTTP, Constants.HTTPS})) {
            return Result.fail("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'http(s)'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), Constants.JOB_ERROR_STR)) {
            return Result.fail("修改任务'" + job.getJobName() + "'失败，目标字符串存在违规");
        } else if (!ScheduleUtils.whiteList(job.getInvokeTarget())) {
            return Result.fail("修改任务'" + job.getJobName() + "'失败，目标字符串不在白名单内");
        }
        return Result.success(jobService.updateJob(job));
    }

    /**
     * 定时任务状态修改
     */
    @PutMapping("/changeStatus")
    public Result changeStatus(@RequestBody SysJob job) throws SchedulerException {
        SysJob newJob = jobService.selectJobById(job.getJobId());
        newJob.setStatus(job.getStatus());
        return Result.success(jobService.changeStatus(newJob));
    }

    /**
     * 定时任务立即执行一次
     */
    @PutMapping("/run")
    public Result run(@RequestBody SysJob job) throws SchedulerException {
        boolean result = jobService.run(job);
        return result ? Result.success() : Result.fail("任务不存在或已过期！");
    }

    /**
     * 删除定时任务
     */
    @DeleteMapping("/{jobIds}")
    public Result remove(@PathVariable Long[] jobIds) throws SchedulerException, TaskException {
        jobService.deleteJobByIds(jobIds);
        return Result.success();
    }
    @GetMapping("/timeExpression")
    @ApiOperation(value = "定时表达式校验", notes = "定时表达式校验")
    public Result<List<String>> checkTimeExpression(String timeExpression,
                                                       @RequestParam(required = false) Long startTime,
                                                       @RequestParam(required = false) Long endTime) {
        try {
            jobService.validate(TimeExpressionType.CRON, timeExpression, startTime, endTime);
            return Result.success(jobService.calculateNextTriggerTimes(TimeExpressionType.CRON, timeExpression, startTime, endTime));
        } catch (Exception e) {
            return Result.success(Lists.newArrayList(ExceptionUtils.getMessage(e)));
        }
    }
}
